<template>
  <div class="login-container">
    <div class="login-background">
      <div class="login-card">
        <div class="login-header">
          <h1 class="login-title">欢迎登录</h1>
          <p class="login-subtitle">请输入您的账号信息</p>
        </div>
        
        <el-form 
          :model="loginForm" 
          :rules="loginRules" 
          ref="loginFormRef" 
          label-position="top"
          class="login-form"
        >
          <el-form-item label="用户名" prop="username">
            <el-input 
              v-model="loginForm.username" 
              prefix-icon="User"
              placeholder="请输入用户名"
              size="large"
              clearable
              @keyup.enter="handleLogin"
            >
            </el-input>
          </el-form-item>
          
          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              prefix-icon="Lock"
              show-password
              placeholder="请输入密码"
              size="large"
              clearable
              @keyup.enter="handleLogin"
            >
            </el-input>
          </el-form-item>
          
          <el-form-item label="验证码" prop="captcha">
            <div class="captcha-container">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                size="large"
                clearable
                @keyup.enter="handleLogin"
              >
              </el-input>
              <div class="captcha-image" @click="refreshCaptcha" title="点击刷新验证码">
                <img
                  v-if="captchaImageUrl"
                  :src="captchaImageUrl"
                  alt="验证码"
                  style="max-width: 100%; max-height: 40px; border-radius: 4px; display: block;"
                />
              </div>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              class="login-button" 
              :loading="userStore.loading" 
              @click="handleLogin"
              size="large"
            >
              {{ userStore.loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="login-footer">
          <p class="copyright">© 2024 管理系统. All rights reserved.</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

import { useUserStore } from '../stores/user';
import axios from 'axios';

const router = useRouter();
const userStore = useUserStore();
const loginFormRef = ref();
const captchaImageUrl = ref('');
const captchaId = ref(''); // 存储验证码ID
const loading = ref(false);

const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
});

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '用户名长度应在 1 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 20, message: '密码长度应在 1 到 20 个字符之间', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
};

// 获取验证码图片和ID
const getCaptcha = async () => {
  try {
    const response = await axios.get('/api/Captcha/GetCaptcha');
    if (response.data && response.data.code === 400) {
      captchaId.value = response.data.data.captchaId;
      captchaImageUrl.value = response.data.data.imageBase64;
    } else {
      ElMessage.error('获取验证码失败');
      captchaImageUrl.value = '';
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
    ElMessage.error('获取验证码失败，请稍后重试');
    captchaImageUrl.value = '';
  }
};

const refreshCaptcha = async () => {
  loginForm.captcha = '';
  await getCaptcha();
  ElMessage.success('验证码已刷新');
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  try {
    const valid = await loginFormRef.value.validate();
    if (valid) {
      loading.value = true;
      const result = await userStore.login({
        userName: loginForm.username,
        password: loginForm.password,
        captchaCode: loginForm.captcha,
        captchaId: captchaId.value
      });

      if (result.success) {
        ElMessage.success('登录成功');
        setTimeout(() => {
          router.push('/EnterpriseManage');
        }, 1500);
      } else {
        ElMessage.error(result.message);
        // 登录失败时刷新验证码
        await getCaptcha();
      }
    } else {
      ElMessage.error('请正确填写登录信息');
      return false;
    }
  } catch (error) {
    console.error('登录失败:', error);
    ElMessage.error('登录失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getCaptcha();
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.login-background {
  width: 100%;
  max-width: 450px;
}

.login-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  border: 1px solid #e1e8ed;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.login-subtitle {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.captcha-image {
  display: flex;
  align-items: center;
  min-width: 120px;
  min-height: 40px;
  background: #fff;
  border-radius: 8px;
  overflow: visible;
}

.captcha-image:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.captcha-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.captcha-image:hover .captcha-overlay {
  opacity: 1;
}

.captcha-overlay .el-icon {
  color: white;
  font-size: 16px;
}

.captcha-loading {
  width: 120px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 4px;
}

.captcha-loading .el-icon {
  font-size: 20px;
  color: #6c757d;
}

.captcha-error {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}

.captcha-error .el-icon {
  font-size: 14px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.4);
}

.login-button:active {
  transform: translateY(0);
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.copyright {
  color: #95a5a6;
  font-size: 12px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }
  
  .login-title {
    font-size: 24px;
  }
  
  .captcha-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .captcha-image {
    align-self: center;
  }
}
</style> 